/**
 *
 */
package com.newer.biz.sys.permission.impil;

import com.baomidou.mybatisplus.plugins.Page;
import com.newer.biz.sys.permission.PermissionBiz;
import com.newer.commons.constants.StateConstants;
import com.newer.commons.result.BizResult;
import com.newer.dao.bean.sys.MenuPermission;
import com.newer.dao.bean.sys.Permission;
import com.newer.dao.bean.sys.User;
import com.newer.dao.commons.dataobject.MenuPermissionDO;
import com.newer.dao.mapper.sys.MenuPermissionMapper;
import com.newer.dao.mapper.sys.PermissionMapper;
import com.newer.dao.mapper.sys.RolePermissionMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.newer.utils.GenIdUtils.genId;
import static com.newer.utils.ShiroAuthUtils.getAuthUser;

/**
 * 权限相关业务操作实现类
 *
 * @author xuntj
 * @create 2018-05-21 19:57
 **/
@Component
public class PermissionBizImpl implements PermissionBiz {

    /**
     * 日志信息打印
     */
    Logger logger = LogManager.getLogger(this.getClass());

    /**
     * 权限信息数据库操作类
     */
    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 菜单权限表数据库操作类
     */
    @Autowired
    MenuPermissionMapper menuPermissionMapper;

    /**
     * 角色权限数据库操作类
     */
    @Autowired
    RolePermissionMapper rolePermissionMapper;


    /**
     * 分页查询所有权限相关信息
     *
     * @param permission
     * @return
     */
    @Override
    public BizResult<Permission> queryPermissionInfoByPage(Permission permission) {
        BizResult<Permission> bizResult = new BizResult<>();
        try {
            // 分页器进行分页
            Page<Permission> pageInfo = new Page<>(permission.getPageNo(), permission.getPageSize());
            // 返回分页结果类
            List<Permission> permissionResult = permissionMapper.selectByParams(pageInfo, permission);
            // 设置分页结果
            pageInfo.setRecords(permissionResult);
            // 设置分页对象
            bizResult.setPageInfo(pageInfo);
            // 返回结果设置
            bizResult.setSuccess(true);
        } catch (Exception e) {
            logger.error("分页查询所有权限相关信息失败,失败原因:" + e.getCause(), e);
            bizResult.setMsg("分页查询所有权限相关信息失败,请联系开发人员.");
        }
        return bizResult;
    }

    /**
     * 添加权限信息
     *
     * @param permission
     * @return
     */
    @Override
    @Transactional
    public BizResult<?> operatePermissionInfo(Permission permission) {
        BizResult<Permission> bizResult = new BizResult<>();
        try {
            // 判断主键ID是否为空,不为空执行修改操作
            if (StringUtils.isNotBlank(permission.getId())) {
                // 更新数据
                permissionMapper.updateByPrimaryKeySelective(permission);
                // 修改菜单权限表的数据
                MenuPermission menuPermission = new MenuPermission();
                menuPermission.setPermissionName(permission.getPermissionName());
                menuPermission.setPermissionId(permission.getId());
                menuPermission.setPermissionCode(permission.getPermissionCode());
                menuPermissionMapper.updateByPrimaryPermissionId(menuPermission);
            } else {
                // 设置主键ID
                permission.setId(genId());
                permission.setStatus(StateConstants.VALIDE);
                User user = getAuthUser(SecurityUtils.getSubject());
                permission.setCreateId(user.getId());
                permission.setCreater(user.getRealName());
                permissionMapper.insertSelective(permission);
            }
            bizResult.setSuccess(true);
        } catch (Exception e) {
            logger.error("添加权限信息失败,失败原因:" + e.getCause(), e);
            bizResult.setMsg("添加权限信息失败,请联系开发人员.");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return bizResult;
    }

    /**
     * 异步校验权限Code
     *
     * @param permissionCode
     * @return
     */
    @Override
    public BizResult<String> checkPermissionCodeExits(String permissionCode) {
        BizResult<String> bizResult = new BizResult<>();
        try {
            String permissionId = permissionMapper.selectPermissionCuntByCode(permissionCode);
            bizResult.setSuccess(true);
            bizResult.setResult(permissionId);
        } catch (Exception e) {
            logger.error("异步校验权限Code失败,失败原因:" + e.getCause(), e);
            bizResult.setMsg("异步校验权限Code失败,请联系开发人员.");
        }
        return bizResult;
    }

    /**
     * 查询所有权限相关信息
     *
     * @param permission
     * @return
     */
    @Override
    public BizResult<Permission> queryMenuDefaultPermissionInfo(MenuPermissionDO permission) {
        BizResult<Permission> bizResult = new BizResult<>();
        try {
            // 返回分页结果类
            List<Permission> permissionResult = menuPermissionMapper.selectMenuDefaultPermissionByParams(permission);
            // 设置分页对象
            bizResult.setResults(permissionResult);
            // 返回结果设置
            bizResult.setSuccess(true);
        } catch (Exception e) {
            logger.error("查询所有权限相关信息失败,失败原因:" + e.getCause(), e);
            bizResult.setMsg("查询所有权限相关信息失败,请联系开发人员.");
        }
        return bizResult;
    }

    /**
     * 查询角色菜单权限信息
     *
     * @param status
     * @param menuIds
     * @return
     */
    @Override
    public BizResult<Permission> queryRoleMenuPermissionsInfo(String roleId, Integer status, List<String> menuIds) {
        BizResult<Permission> bizResult = new BizResult<>();
        try {
            // 返回分页结果类
            List<Permission> permissionResult = menuPermissionMapper.selectRoleMenuPermissions(roleId, status, menuIds);
            // 设置分页对象
            bizResult.setResults(permissionResult);
            // 返回结果设置
            bizResult.setSuccess(true);
        } catch (Exception e) {
            logger.error("查询角色菜单权限信息失败,失败原因:" + e.getCause(), e);
            bizResult.setMsg("查询角色菜单权限信息失败,请联系开发人员.");
        }
        return bizResult;
    }

    /**
     * 根据Id查询权限信息
     *
     * @param id
     * @return
     */
    @Override
    public BizResult<Permission> queryPermissionById(String id) {
        BizResult<Permission> bizResult = new BizResult<>();
        try {
            // 分页器进行分页
            // 返回分页结果类
            Permission permission = permissionMapper.selectByPrimaryKey(id);
            // 设置分页对象
            bizResult.setResult(permission);
            // 返回结果设置
            bizResult.setSuccess(true);
        } catch (Exception e) {
            logger.error("根据Id查询权限信息失败,失败原因:" + e.getCause(), e);
            bizResult.setMsg("根据Id查询权限信息失败,请联系开发人员.");
        }
        return bizResult;
    }

    /**
     * 根据Id删除权限信息
     *
     * @param id
     * @return
     */
    @Override
    public BizResult<?> validStatus(String id, Integer status) {
        BizResult<?> bizResult = new BizResult<>();
        try {
            Permission permission = new Permission();
            permission.setId(id);
            permission.setStatus(status);
            permissionMapper.updateByPrimaryKeySelective(permission);
            // 判断是否删除操作
            if (StateConstants.UN_VALIDE.equals(status)) {
                // 删除菜单权限信息
                Map<String, Object> maps = new HashMap<>();
                maps.put("permission_id", id);
                // 删除所有关联数据
                menuPermissionMapper.deleteByMap(maps);
                // 删除所有相关数据
                rolePermissionMapper.deleteByMap(maps);
            }
            bizResult.setSuccess(true);
        } catch (Exception e) {
            logger.error("删除菜单信息失败,失败原因:" + e.getCause(), e);
            bizResult.setMsg("删除菜单信息失败,请联系开发人员.");
        }
        return bizResult;
    }
}
